package com.qire.manhua.dal.service;

import com.qire.antsbinder.dal.DataService;
import com.qire.antsbinder.dal.annotation.StrategyAnnotation;
import com.qire.common.basic.ObjectUtil;
import com.qire.common.collect.ListUtil;
import com.qire.common.constant.Url;
import com.qire.common.dal.WarehouseFactory;
import com.qire.common.utils.ToastHelper;
import com.qire.manhua.dal.IComicDataDAL;
import com.qire.manhua.dal.dao.ComicDatabase;
import com.qire.manhua.dal.dao.ComicReadHistoryDao;
import com.qire.manhua.model.entity.ComicBookEntity;
import com.qire.manhua.model.po.ComicReadHistoryRecord;
import com.qire.manhua.model.viewModel.impl.BookshelfHistoryViewModel;
import com.qire.manhua.model.vo.ComicReadHistoryVO;
import com.qire.manhua.model.vo.OkResponseVO;

import java.util.List;

public class HomeBookshelfHistoryService extends DataService {

    private IComicDataDAL comicDataDAL = WarehouseFactory.create(this, IComicDataDAL.class);
    private ComicReadHistoryDao comicReadHistoryDao = ComicDatabase.database().comicReadHistoryDao();

    private BookshelfHistoryViewModel viewModel;

    public HomeBookshelfHistoryService(BookshelfHistoryViewModel viewModel) {
        this.viewModel = viewModel;
    }

    public void uploadBookshelfHistory() {
        List<ComicReadHistoryRecord> historyList =  comicReadHistoryDao.queryAll();
    }

    public void loadBookshelfHistory() {
        comicDataDAL.fetchReadHistoryRecord(0);
    }
    @StrategyAnnotation(event = Url.HomeBookshelfHistoryComicList)
    public void fetchReadHistoryRecordApiCallback(List<ComicReadHistoryVO> dataVOList, boolean isCache) {
        viewModel.refreshLayoutFinish(300);
        viewModel.clearHistoryList();

        if(ListUtil.notEmpty(dataVOList)) {
            for(ComicReadHistoryVO vo : dataVOList) {
                ComicBookEntity comicBookEntity = vo.toComicBookEntity();
                if(ObjectUtil.nonNull(comicBookEntity)) {
                    viewModel.addHistoryItem(comicBookEntity, vo.lastReadRecord(), vo.lastUpdateTime(), vo.updateChapterInfo());
                }
            }
        }

        viewModel.refreshHistoryAdapter();
        viewModel.refreshEmptyDataUI(false);
    }

    public void batchRemoveBookshelfHistory(List<String> comicIdList) {
        comicDataDAL.removeReadHistoryRecord(comicIdList);
    }
    @StrategyAnnotation(event = Url.my_user_read_delete)
    public void removeReadHistoryRecordApiCallback(OkResponseVO dataVO, boolean isCache) {
        if(ObjectUtil.isNull(dataVO)) {
            return ;
        }
        if(dataVO.isOK()) {
            viewModel.clearBatchDeleteList();
            loadBookshelfHistory();
            ToastHelper.showToast("已经从记录移除");
        } else {
            ToastHelper.showToast("移除操作失败");
        }
    }

}
